package handlers

import (
	"fmt"
	"strconv"
	"time"

	"sales-web/server/dal"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type OrderDetail struct {
	ID                  int64      `json:"id"`
	UserID              int64      `json:"user_id"`
	ProductName         string     `json:"product_name"`
	Country             string     `json:"country"`
	Price               float32    `json:"price"`
	CostPrice           float32    `json:"cost_price"`
	Count               int64      `json:"count"`          // 实际结算量
	CustomerCount       int64      `json:"customer_count"` // 客户下单量
	CompleteCount       int64      `json:"complete_count"` // 实际完成量
	CustomerName        string     `json:"customer_name"`
	PayType             string     `json:"pay_type"`  // 收款类型 usdt/支付宝/微信
	PayValue            float32    `json:"pay_value"` // 收款金额
	PayTime             *time.Time `json:"pay_time"`
	ReturnType          string     `json:"return_type"`  // 反点类型 usdt/支付宝/微信
	ReturnValue         float32    `json:"return_value"` // 反点金额
	ReturnTime          *time.Time `json:"return_time"`
	RefundType          string     `json:"refund_type"`  // 退款类型
	RefundValue         float32    `json:"refund_value"` // 退款金额
	FinalType           string     `json:"final_type"`   // 尾款类型
	FinalValue          float32    `json:"final_value"`  // 尾款金额
	FinalTime           *time.Time `json:"final_time"`
	RefundTime          *time.Time `json:"refund_time"`
	Comment             string     `json:"comment"`            // 备注
	UsdtExchangeRate    float32    `json:"usdt_exchange_rate"` // usdt汇率
	OrderCreateTime     time.Time  `json:"order_create_time"`
	CreatedAt           time.Time  `json:"created_at"`
	UpdatedAt           time.Time  `json:"updated_at"`
	Username            string     `json:"username"`
	Nickname            string     `json:"nickname"`
	DispatchUsername    string     `json:"dispatch_username"`
	DispatchNickname    string     `json:"dispatch_nickname"`
	DispatchComment     string     `json:"dispatch_comment"`
	DispatchUserComment string     `json:"dispatch_user_comment"` // 派单用户自己的备注
}

const DateLayout = "2006-01-02"

func (h *Handler) QueryOrder(c *gin.Context) {
	user := GetCurrentUser(c)
	var result = []OrderDetail{}
	query := h.dbc.Table("customer_order").
		Joins("left join user on user.id=customer_order.user_id").Joins("left join user dispatch_user on dispatch_user.id=customer_order.dispatch_user_id").
		Select("customer_order.*,user.username as username,user.nickname as nickname," +
			"dispatch_user.username as dispatch_username,dispatch_user.nickname as dispatch_nickname")

	username := c.Request.URL.Query().Get("username")
	orderCreateTime, createTimeExist := c.GetQueryArray("order_create_time")
	country := c.Request.URL.Query().Get("country")
	if user.Role == "user" {
		query = query.Where("user_id=?", user.ID)
	}
	if user.Role == "dispatch_user" {
		query = query.Where("dispatch_user_id=?", user.ID)
	}
	if username != "" {
		query = query.Where("user.username=?", username)
	}
	if country != "" {
		query = query.Where("country=?", country)
	}
	if createTimeExist && len(orderCreateTime) == 2 {
		startTime, err := time.Parse(DateLayout, orderCreateTime[0])
		if err != nil {
			SendErrResp(c, 400, err)
			return
		}
		endTime, err := time.Parse(DateLayout, orderCreateTime[1])
		if err != nil {
			SendErrResp(c, 400, err)
			return
		}
		query = query.Where("order_create_time > ? and order_create_time < ?", startTime.Format(DateLayout), endTime.Add(time.Hour*24).Format(DateLayout))
	}
	query.Order("order_create_time desc")
	err := query.Scan(&result).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}
	SendOkResp(c, result)
}

func (h *Handler) checkOrder(request dal.CustomOrder) error {
	var country dal.Country
	err := h.dbc.Where("name=?", request.Country).First(&country).Error
	if err != nil {
		return fmt.Errorf("country not found,err: %s", err)
	}
	if country.LimitPrice > int64(request.Price) {
		return fmt.Errorf("价格不能低于最低价:%d", country.LimitPrice)
	}
	if request.RefundType == "usdt" || request.PayType == "usdt" || request.ReturnType == "usdt" || request.FinalType == "usdt" {
		if request.UsdtExchangeRate <= 0 {
			return fmt.Errorf("USDT汇率不能为空")
		}
	}
	return nil
}
func (h *Handler) CreateOrder(c *gin.Context) {
	user := GetCurrentUser(c)
	var request dal.CustomOrder
	err := c.BindJSON(&request)
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}
	err = h.checkOrder(request)
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}
	var country dal.Country
	err = h.dbc.Where("name=?", request.Country).First(&country).Error
	if err != nil {
		SendErrResp(c, 400, fmt.Errorf("country not found,err: %s", err))
		return
	}
	request.CostPrice = country.CostPrice
	request.UserID = user.ID
	err = h.dbc.Create(&request).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}
	SendOkResp(c, request)
}

func (h *Handler) DeleteOrder(c *gin.Context) {
	idStr, _ := c.Params.Get("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}
	var item dal.CustomOrder
	err = h.dbc.Where("id= ?", id).First(&item).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}
	err = h.dbc.Delete(&item).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}

	SendOkResp(c, "")
}

func (h *Handler) UpdateOrder(c *gin.Context) {
	idStr, _ := c.Params.Get("id")
	user := GetCurrentUser(c)
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		SendErrResp(c, 400, fmt.Errorf("faield to parse id, err:%s", err))
		return
	}
	var request dal.CustomOrder
	err = c.BindJSON(&request)
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}
	err = h.checkOrder(request)
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}
	var item dal.CustomOrder
	err = h.dbc.Where("id= ?", id).First(&item).Error
	if err != nil {
		SendErrResp(c, 400, err)
		return
	}
	if user.Role != "super_admin" && time.Now().Sub(item.CreatedAt).Hours() > 72 {
		SendErrResp(c, 500, fmt.Errorf("超过3天不能修改，创建时间%s", time.Now()))
		return
	}
	item.ProductName = request.ProductName
	item.Country = request.Country
	item.Price = request.Price
	item.Count = request.Count
	item.Comment = request.Comment
	item.CustomerName = request.CustomerName
	item.OrderCreateTime = request.OrderCreateTime
	item.PayValue = request.PayValue
	item.PayType = request.PayType
	item.RefundValue = request.RefundValue
	item.RefundType = request.RefundType
	item.ReturnValue = request.ReturnValue
	item.ReturnType = request.ReturnType
	item.UsdtExchangeRate = request.UsdtExchangeRate
	item.PayTime = request.PayTime
	item.RefundTime = request.RefundTime
	item.ReturnTime = request.ReturnTime
	item.FinalType = request.FinalType
	item.FinalValue = request.FinalValue
	item.FinalTime = request.FinalTime
	err = h.dbc.Save(&item).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}
	SendOkResp(c, "")
}

type OrderSummaryInfo struct {
	TotalPrice  float32 `json:"total_price"`
	TotalPay    float32 `json:"total_pay"`
	TotalReturn float32 `json:"total_return"`
	TotalRefund float32 `json:"total_refund"`
	TotalProfit float32 `json:"total_profit"`
	Count       int     `json:"count"`
}

func (h *Handler) GetOrderSummary(c *gin.Context) {
	var result OrderSummaryInfo
	var todayResult OrderSummaryInfo
	orderCreateTime := c.Request.URL.Query().Get("order_create_time")
	now := time.Now()
	nextDay := now.Add(time.Hour * 24)
	todayQuery := h.OrderSummaryQuery(c, &now, &nextDay)
	err := todayQuery.Scan(&todayResult).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}

	totalQuery := h.OrderSummaryQuery(c, nil, nil)
	if orderCreateTime != "" {
		parsedTime, err := time.Parse(DateLayout, orderCreateTime)
		if err != nil {
			SendErrResp(c, 400, err)
			return
		}
		totalQuery = totalQuery.Where("order_create_time > ? and order_create_time < ?", orderCreateTime, parsedTime.Add(time.Hour*24).Format(DateLayout))
	}
	err = totalQuery.Scan(&result).Error
	if err != nil {
		SendErrResp(c, 500, err)
		return
	}
	SendOkResp(c, map[string]interface{}{"today": todayResult, "total": result})
}

func (h *Handler) OrderSummaryQuery(c *gin.Context, startDate *time.Time, endDate *time.Time) *gorm.DB {
	user := GetCurrentUser(c)
	query := h.dbc.Table("customer_order").
		Joins("left join user on user.id=customer_order.user_id").
		Joins("left join country on country.name=customer_order.country").
		Select(`SUM(price*count) as total_price,
SUM(pay_value) as total_pay,
SUM(return_value) as total_return,
SUM(refund_value) as total_refund,
SUM((customer_order.price-customer_order.cost_price)*customer_order.count) as total_profit,
Count(1) as count
`)

	username := c.Request.URL.Query().Get("username")
	country := c.Request.URL.Query().Get("country")
	if user.Role == "user" {
		query = query.Where("user_id=?", user.ID)
	}
	if country != "" {
		query = query.Where("country=?", country)
	}
	if username != "" {
		query = query.Where("user.username=?", username)
	}
	if startDate != nil && endDate != nil {
		query = query.Where("order_create_time > ? and order_create_time < ?", startDate.Format(DateLayout), endDate.Format(DateLayout))
	}
	return query
}
